"""
测试执行管理API
"""

from flask import Blueprint, request
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required
from app.services.executor import TestExecutor
from app.models.test_case import TestCase
from app.models.report import Report
from app.tasks.execution_tasks import execute_test_batch
from app import db
import uuid
from datetime import datetime

execution_bp = Blueprint('execution', __name__, url_prefix='/api/executions')


@execution_bp.route('/start', methods=['POST'])
def start_execution():
    """
    启动测试执行
    
    请求体:
    {
        "project_id": 1,
        "project_name": "项目名称",
        "base_url": "http://api.example.com",
        "case_ids": ["case1", "case2"],  # 用例ID列表
        "data_source_config": {  # 可选，数据驱动配置
            "type": "excel",
            "config": {
                "file_path": "/path/to/data.xlsx"
            }
        }
    }
    """
    try:
        data = request.get_json()
        
        # 验证必需字段
        required_fields = ['project_id', 'project_name', 'base_url', 'case_ids']
        for field in required_fields:
            if field not in data:
                return error_response(f"缺少必需字段: {field}")
        
        project_id = data['project_id']
        project_name = data['project_name']
        base_url = data['base_url']
        case_ids = data['case_ids']
        data_source_config = data.get('data_source_config')
        
        # 查询测试用例
        test_cases = TestCase.query.filter(TestCase.case_id.in_(case_ids)).all()
        
        if not test_cases:
            return error_response("未找到指定的测试用例")
        
        # 转换为字典格式
        cases_data = []
        for case in test_cases:
            cases_data.append({
                'case_id': case.case_id,
                'case_name': case.case_name,
                'url': case.url,
                'method': case.method,
                'parameters': eval(case.parameters) if case.parameters else [],
                'body': eval(case.body) if case.body else None,
                'assertions': eval(case.assertions) if case.assertions else []
            })
        
        # 创建报告记录
        report_id = f"report_{uuid.uuid4().hex[:16]}"
        report = Report(
            report_id=report_id,
            project_id=project_id,
            project_name=project_name,
            generate_time=datetime.now(),
            total_cases=len(cases_data),
            total_executions=0,
            success_count=0,
            failed_count=0,
            pass_rate=0.0
        )
        db.session.add(report)
        db.session.commit()
        
        # 构造任务配置
        task_config = {
            'project_id': project_id,
            'project_name': project_name,
            'base_url': base_url,
            'test_cases': cases_data,
            'data_source_config': data_source_config,
            'report_id': report_id
        }
        
        # 提交异步任务
        task = execute_test_batch.apply_async(args=[task_config])
        
        return success_response({
            'task_id': task.id,
            'report_id': report_id,
            'status': 'started'
        })
        
    except Exception as e:
        return error_response(f"启动执行失败: {str(e)}")


@execution_bp.route('/<task_id>/status', methods=['GET'])
def get_execution_status(task_id):
    """
    查询执行状态
    """
    try:
        from app.tasks.execution_tasks import celery_app
        
        task = celery_app.AsyncResult(task_id)
        
        if task.state == 'PENDING':
            response = {
                'state': task.state,
                'status': '等待中...',
                'progress': 0
            }
        elif task.state == 'PROGRESS':
            response = {
                'state': task.state,
                'status': task.info.get('status', ''),
                'progress': task.info.get('progress', 0)
            }
        elif task.state == 'SUCCESS':
            response = {
                'state': task.state,
                'status': '完成',
                'progress': 100,
                'result': task.info
            }
        elif task.state == 'FAILURE':
            response = {
                'state': task.state,
                'status': '失败',
                'progress': 0,
                'error': str(task.info)
            }
        else:
            response = {
                'state': task.state,
                'status': '未知状态',
                'progress': 0
            }
        
        return success_response(response)
        
    except Exception as e:
        return error_response(f"查询状态失败: {str(e)}")


@execution_bp.route('/<task_id>/cancel', methods=['POST'])
def cancel_execution(task_id):
    """
    取消执行任务
    """
    try:
        from app.tasks.execution_tasks import celery_app
        
        celery_app.control.revoke(task_id, terminate=True)
        
        return success_response({'status': 'cancelled'})
        
    except Exception as e:
        return error_response(f"取消任务失败: {str(e)}")


@execution_bp.route('/quick-test', methods=['POST'])
def quick_test():
    """
    快速测试单个用例（同步执行）
    
    请求体:
    {
        "base_url": "http://api.example.com",
        "test_case": {
            "case_id": "test_case_1",
            "case_name": "测试用例",
            "url": "/api/test",
            "method": "GET",
            "parameters": [],
            "body": null,
            "assertions": []
        }
    }
    """
    try:
        data = request.get_json()
        
        if 'base_url' not in data or 'test_case' not in data:
            return error_response("缺少必需字段")
        
        base_url = data['base_url']
        test_case = data['test_case']
        
        # 创建执行器并执行
        executor = TestExecutor(base_url)
        result = executor.execute_case(test_case)
        
        return success_response(result)
        
    except Exception as e:
        return error_response(f"执行失败: {str(e)}")
